package com.study.thread.classtest;

import java.util.concurrent.CountDownLatch;

/**
 * 等待子任务执行完毕后，才可继续执行主线程的任务
 */
public class CountDownLatchTest {
    public static void main(String[] args) {
        try {
            final CountDownLatch latch = new CountDownLatch(2);
            new Thread(){public void run(){
                try {
                    System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}.start();
            new Thread(){public void run(){
                try {
                    System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}.start();
            System.out.println("等待2个子线程执行结束");
            latch.await();
            System.out.println("2个子线程执行结束");
            System.out.println("主线程可以继续做事");
            //子线程Thread-0正在执行
            //等待2个子线程执行结束
            //子线程Thread-1正在执行
            //子线程Thread-0执行完毕
            //子线程Thread-1执行完毕
            //2个子线程执行结束
            //主线程可以继续做事
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
